import ImageUpload from '@/components/ImageUpload';
import { Col, DatePicker, Form, InputNumber, Modal, Row, Select } from 'antd';
import { useEffect } from 'react';

const { Option } = Select;

interface RoomInfo {
  id: string;
  roomType: string;
  orientation: string;
  innerArea: number;
  monthlyRent: number;
  rentalStatus: string;
  imageList: string[];
  sortOrder: number;
  viewingPeriod?: string;
  moveInDate?: string;
  paymentCycleList?: string[];
  cycleAndRentList?: Array<{
    paymentCycle: string;
    monthlyRent: number;
  }>;
}

interface RoomEditModalProps {
  visible: boolean;
  onCancel: () => void;
  onOk: (roomData: RoomInfo) => void;
  editingRoom?: RoomInfo | null;
  isEdit?: boolean;
}

// 房间类型选项
const roomTypeOptions = [
  { label: '主卧', value: '主卧' },
  { label: '次卧', value: '次卧' },
  { label: '书房', value: '书房' },
  { label: '储物间', value: '储物间' },
];

// 朝向选项
const orientationOptions = [
  { label: '南', value: '南' },
  { label: '北', value: '北' },
  { label: '东', value: '东' },
  { label: '西', value: '西' },
  { label: '东南', value: '东南' },
  { label: '西南', value: '西南' },
  { label: '东北', value: '东北' },
  { label: '西北', value: '西北' },
];

// 房间状态选项
const roomStatusOptions = [
  { label: '可出租', value: '可出租' },
  { label: '已出租', value: '已出租' },
  { label: '维修中', value: '维修中' },
];

// 看房时间选项
const viewingPeriodOptions = [
  { label: '随时看房', value: '随时看房' },
  { label: '预约看房', value: '预约看房' },
  { label: '周末看房', value: '周末看房' },
];

// 支付周期选项
const paymentCycleOptions = [
  { label: '月付', value: '月付' },
  { label: '季付', value: '季付' },
  { label: '半年付', value: '半年付' },
  { label: '年付', value: '年付' },
];

const RoomEditModal: React.FC<RoomEditModalProps> = ({
  visible,
  onCancel,
  onOk,
  editingRoom,
  isEdit = false,
}) => {
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible && editingRoom) {
      // 初始化支付周期数据
      let paymentCycle = '月付';
      let monthlyRent = 1;

      if (editingRoom.paymentCycleList && editingRoom.cycleAndRentList) {
        // 使用第一个支付周期
        paymentCycle = editingRoom.paymentCycleList[0] || '月付';
        monthlyRent =
          editingRoom.cycleAndRentList.find(
            (item) => item.paymentCycle === paymentCycle,
          )?.monthlyRent || 0;
      } else {
        // 兼容旧数据，使用单一租金
        monthlyRent = editingRoom.monthlyRent || 0;
      }

      form.setFieldsValue({
        roomType: editingRoom.roomType,
        orientation: editingRoom.orientation,
        innerArea: editingRoom.innerArea,
        paymentCycle: paymentCycle,
        monthlyRent: monthlyRent,
        rentalStatus: editingRoom.rentalStatus,
        viewingPeriod: editingRoom.viewingPeriod || '',
        moveInDate: editingRoom.moveInDate || '',
        roomImages: editingRoom.imageList || [],
      });
    } else if (visible && !isEdit) {
      form.resetFields();
      // 设置默认值
      form.setFieldsValue({
        paymentCycle: '月付',
        monthlyRent: 1,
        roomImages: [],
      });
    }
  }, [visible, editingRoom, form, isEdit]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const roomData: RoomInfo = {
        id: editingRoom?.id || Date.now().toString(),
        roomType: values.roomType,
        orientation: values.orientation,
        innerArea: values.innerArea,
        monthlyRent: values.monthlyRent,
        rentalStatus: values.rentalStatus,
        imageList: values?.roomImages || [],
        sortOrder: editingRoom?.sortOrder || 1,
        viewingPeriod: values.viewingPeriod,
        moveInDate: values.moveInDate,
        paymentCycleList: values.paymentCycle ? [values.paymentCycle] : [],
        cycleAndRentList: values.paymentCycle
          ? [
              {
                paymentCycle: values.paymentCycle,
                monthlyRent: values.monthlyRent,
              },
            ]
          : [],
      };
      onOk(roomData);
    } catch (error) {
      console.log('表单验证失败:', error);
    }
  };

  return (
    <Modal
      title={isEdit ? '编辑房间信息' : '添加房间信息'}
      open={visible}
      onCancel={onCancel}
      onOk={handleOk}
      width={600}
      destroyOnClose
    >
      <Form form={form} layout="vertical">
        {/* 第一行：房间类型 | 朝向 */}
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="房间类型"
              name="roomType"
              rules={[{ required: true, message: '请选择房间类型' }]}
            >
              <Select placeholder="请选择房间类型">
                {roomTypeOptions.map((option) => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="朝向"
              name="orientation"
              rules={[{ required: true, message: '请选择朝向' }]}
            >
              <Select placeholder="请选择朝向">
                {orientationOptions.map((option) => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        {/* 第二行：面积 | 房间出租状态 */}
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="面积"
              name="innerArea"
              rules={[{ required: true, message: '请输入房间面积' }]}
            >
              <InputNumber
                style={{ width: '100%' }}
                placeholder="请输入房间面积"
                addonAfter="㎡"
                min={0}
                precision={1}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="房间出租状态"
              name="rentalStatus"
              rules={[{ required: true, message: '请选择房间出租状态' }]}
            >
              <Select placeholder="请选择房间出租状态">
                {roomStatusOptions.map((option) => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        {/* 第三行：支付周期 | 月租金 */}
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="支付周期"
              name="paymentCycle"
              rules={[{ required: true, message: '请选择支付周期' }]}
            >
              <Select placeholder="请选择支付周期" style={{ width: '100%' }}>
                {paymentCycleOptions.map((option) => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="月租金"
              name="monthlyRent"
              rules={[
                { required: true, message: '请输入月租金' },
                {
                  validator: (_rule, value) => {
                    if (value < 1) {
                      return Promise.reject(new Error('月租金不能小于1'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <InputNumber
                style={{ width: '100%' }}
                placeholder="请输入月租金"
                addonBefore="¥"
                addonAfter="元/月"
                min={1}
                precision={2}
              />
            </Form.Item>
          </Col>
        </Row>

        {/* 第四行：看房时间 | 可入住时间 */}
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="看房时间"
              name="viewingPeriod"
              rules={[{ required: true, message: '请选择看房时间' }]}
            >
              <Select placeholder="请选择看房时间">
                {viewingPeriodOptions.map((option) => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="可入住时间"
              name="moveInDate"
              rules={[{ required: true, message: '请选择可入住时间' }]}
            >
              <DatePicker
                style={{ width: '100%' }}
                placeholder="请选择可入住时间"
                format="YYYY-MM-DD"
              />
            </Form.Item>
          </Col>
        </Row>

        {/* 房间图片 - 单独一行 */}
        <Form.Item
          label="房间图片"
          name="roomImages"
          rules={[{ required: true, message: '请上传房间图片' }]}
        >
          <div style={{ marginBottom: 8, fontSize: 12, color: '#666' }}>
            添加房间图片（至少1张）
          </div>
          <Form.Item name="roomImages" noStyle>
            <ImageUpload maxCount={5} />
          </Form.Item>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default RoomEditModal;
